package com.dcivision.framework.taglib.bean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.struts.config.ActionConfig;

import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractSearchForm;

/**
 * Put opMode and navMode in servlet request scope.
 *
 * @author TC Tang
 *
 */
public class ActionModeTag extends BodyTagSupport{

  public int doStartTag() throws JspException {
    setActionMode();
    return(SKIP_BODY);
  }
  public int doEndTag() throws JspException {
    return EVAL_PAGE;
  }
  protected void setActionMode() {

    String formNavMode = "";
    String formOptMode = "";
    String actionMode = "";
    Object formObj = null;

    HttpServletRequest request = (HttpServletRequest)this.pageContext.getRequest();
    ActionConfig actionConfig = (ActionConfig)this.pageContext.getRequest().getAttribute("org.apache.struts.action.mapping.instance");
    String formName=actionConfig.getName();//formName

    if(!Utility.isEmpty(request.getAttribute(GlobalConstant.ACTION_MODE))){
      //if request have the action_mode,keep it
      return ;
    }
    if(!Utility.isEmpty(formName)){
      formObj = this.pageContext.getRequest().getAttribute(formName) ;
    }

    if(!Utility.isEmpty(formObj)){

      if (formObj instanceof AbstractSearchForm) {
      // Case of List Search Action
        actionMode = GlobalConstant.NAV_MODE_LIST;
        request.setAttribute(GlobalConstant.ACTION_MODE, actionMode);

      } else if (formObj instanceof AbstractActionForm) {
      // Case of Maint Action
        AbstractActionForm actionForm = (AbstractActionForm)formObj;
        formNavMode = actionForm.getNavMode();
        formOptMode = actionForm.getOpMode();
        if (Utility.isEmpty(formNavMode) || GlobalConstant.NAV_MODE_NEW.equals(formNavMode)) {
        // Create New Record Action
          actionMode = GlobalConstant.NAV_MODE_NEW;
        //this.textOnly = false;
        } else {
          actionMode = formNavMode;
        }
        request.setAttribute(GlobalConstant.ACTION_MODE, actionMode);

      }
   }

  }
}
